package com.yntsoft.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springside.modules.cache.memcached.SpyMemcachedClient;
import org.springside.modules.mapper.JsonMapper;

@Component
public class BaseService {

	@Autowired(required = false)
	protected SpyMemcachedClient memcachedClient;
	
	protected final JsonMapper jsonMapper = JsonMapper.nonDefaultMapper();
	
	/**
	 * 得到单个实体当前缓存的版本号
	 * @param key
	 * @return
	 */
	protected Integer getMemcachedVersion(String key){ 
        if (memcachedClient != null){
        	String jsonString = memcachedClient.get(key);
    		if (jsonString != null) 
    			return jsonMapper.fromJson(jsonString,Integer.class);
    		else 
    			return 0;
		} else 
			return 0;
	} 
	
	
	/**
	 * 修改、删除时，版本号+1，缓存就失效 
	 * @param key
	 * @param expiredTime
	 */
	protected void setMemcachedVersion(String key,Integer expiredTime){ 
        Integer versionNum = this.getMemcachedVersion(key);
        if (memcachedClient != null){
        	versionNum++; 
        	String jsonString = jsonMapper.toJson(versionNum);
			memcachedClient.set(key,expiredTime,jsonString);
        }
    }
	
	
	
	/**
	 * 得到当前分页缓存的版本号
	 * @param key
	 * @return
	 */
	protected Integer getPageMemcachedVersion(String key){ 
        if (memcachedClient != null){
        	String jsonString = memcachedClient.get(key);
    		if (jsonString != null) 
    			return jsonMapper.fromJson(jsonString,Integer.class);
    		else 
    			return 0;
		} else 
			return 0;
	} 
	
	/**
	 * 增加、修改、删除时，版本号+1，分页缓存就失效 
	 * @param key
	 * @param expiredTime
	 */
	protected void setPageMemcachedVersion(String key,Integer expiredTime){ 
        Integer versionNum = this.getPageMemcachedVersion(key);
        if (memcachedClient != null){
        	 versionNum++; 
        	String jsonString = jsonMapper.toJson(versionNum);
			memcachedClient.set(key,expiredTime,jsonString);
        }
    }
	
}
